<?php
/**
 *	KLF Framework
 *
 *	Written by Kristian Oye <kristianoye@gmail.com> on Oct 26, 2011
 *	Copyright (C) 2010-2011
 */
namespace KLF\System\Web
{
	use KLF\KCore;
	use KLF\System\Web\KHttpApplication;
	use KLF\System\Config\KConfiguration;
	use KLF\System\Web\Routing\KRouteCollection;
	use KLF\System\Web\Routing\KUrlRoutingModule;
	use KLF\System\Errors\KNotImplementedException;
	
	/**
	 *  Class KMvcApplication
	 *
	 *  An MVC Application
	 *
	 *  @package KLF\System\Web
	 *  @access public
	 *  @author Kristian Oye <kristianoye@gmail.com>
	 *  @since 0.1
	 *  
	 *  @method KMvcApplication NewInstance
	 *  
	 *  @property KRouteCollection $Routes
	 *  
	 */
	abstract class KMvcApplication extends KHttpApplication
	{
		public function __construct(KConfiguration $config)
		{
			$directoryName = realpath($config->GetValue('ContentDirectory')
				. DIRECTORY_SEPARATOR . $config->GetValue('CodeDirectory'));
			
			if (is_dir($directoryName))
			{
				KCore::AddAutoloadDirectories($directoryName);
			}
			parent::__construct($config);
		}
		
		/**
		 * Contains the mapped routes within the application.
		 * 
		 * @var KRouteCollection $_rpropRoutes
		 */
		protected $_rpropRoutes;
		
		/**
		 * Initialize the application.
		 * 
		 * @see \KLF\System\Web\KHttpApplication::Initialize()
		 */
		protected function Initialize()
		{
			parent::Initialize();
			$this->_rpropRoutes = new KRouteCollection();
			static::RegisterRoutes($this->_rpropRoutes);
		}
		
		/**
		 * Registers MVC routes handled by the application.
		 * 
		 * @param KRouteCollection $routes
		 */
		abstract public static function RegisterRoutes(KRouteCollection &$routes);
		
		/**
		 * Runs the MVC application.
		 * 
		 * @see KLF\System\Web.KHttpApplication::RunApplication()
		 */
		protected function RunApplication()
		{
			parent::RunApplication();
		}
		
		/**
		 * Override the default HTTP application behavior with MVC.  This step
		 * inspects the routes to determine which route was matched and then
		 * dispatches the request.
		 * 
		 * @see KLF\System\Web.KHttpApplication::StartApplication()
		 */
		protected function StartApplication()
		{
			$router = new KUrlRoutingModule($this->_rpropRoutes);
			$router->Initialize($this);
			
			if(($requestContext = $router->ResolveRequest()))
			{
				$this->Context->Handler = $requestContext->RouteData->RouteHandler->GetHttpHandler($requestContext);
			}
			parent::StartApplication();
		}
		
		/**
		 * Unload the application prior to the thread exiting.
		 * 
		 * @see KLF\System\Web.KHttpApplication::UnloadApplication()
		 */
		protected function UnloadApplication()
		{
			parent::UnloadApplication();
		}
	}
}